import 'dart:async';

import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/vg_reg_exp_utils.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_widget_lib.dart';


import 'constant/common_sms_code_constant.dart';
import 'service/common_sms_code_service.dart';

///拿到电话号码回调
typedef CommonSmsCodeGetPhoneFunc = String Function();

///回调倒计时自定义组件
typedef CommonSmsCodeGetDownWidgetFunc = Widget Function(int downValue);



///通用验证码组件（含倒计时，和发送验证码逻辑）
class CommonSmsCodeWidget extends StatefulWidget {

  ///默认样式组件
  final Widget child;

  ///获取电话号码(回调前，先格式检测或提示)
  final CommonSmsCodeGetPhoneFunc phoneFunc;

  ///自定义倒计时组件
  final CommonSmsCodeGetDownWidgetFunc downCustomWidget;

  ///重新发送样式组件
  final Widget resetChild;

  final bool login;

  const CommonSmsCodeWidget({Key key, this.child, this.phoneFunc, this.downCustomWidget, this.resetChild, this.login}) :
        assert(phoneFunc != null , "手机号码回调不能为空"),
        super(key: key);

  @override
  _CommonSmsCodeWidgetState createState() => _CommonSmsCodeWidgetState();
}

class _CommonSmsCodeWidgetState extends BaseState<CommonSmsCodeWidget> {
  
  ///计时器
  Timer _timer;

  ///1秒
  Duration oneSecond = const Duration(milliseconds: 1000);

  ///计时数
  int _codeCountDown = CommonSmsCodeConstant.DEFAULT_TIMER;

  ///是否显示重新发送
  bool _isShowReset = false;

  CommonSmsCodeService _service;

  @override
  void initState() {
    if(widget?.login??false){
      _isShowReset = true;
      _startTimer();
      setState(() { });
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return _toMainWidget();
  }

  Widget _toMainWidget(){
      return _codeCountDown >= CommonSmsCodeConstant.DEFAULT_TIMER
      ? _toGestureWidget()
      : _toDownWidget();
  }

  Widget _toGestureWidget() {
    return GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {
          if(widget?.phoneFunc == null){
            ToastUtils.toast(context: context,msg: "手机号码获取失败");
            return;
          }
          String phone = widget?.phoneFunc();
          //回调前先格式检测或提示
          if(StringUtils.isEmpty(phone)){
            return;
          }
          _httpSendSmsCode(phone);
        },
        child: _toChildWidget());
  }

  Widget _toChildWidget() {
    if(_isShowReset){
      return widget?.resetChild ?? _defaultResetChildWidget();
    }else{
      return widget?.child ?? _defaultChildWidget();
    }
  }

  Widget _toDownWidget(){
    return widget?.downCustomWidget != null ?widget?.downCustomWidget(_codeCountDown) :_defaultDownWidget();
  }


  ///开启计时器
  void _startTimer(){
    if(_timer?.isActive ?? false){
      return;
    }
    _proccessSetState();
    _timer = Timer.periodic(oneSecond, (timer) {
      _proccessSetState();
    });
  }

  void _proccessSetState(){
    _codeCountDown = _codeCountDown - 1;
    if(_codeCountDown <= 0){
      _codeCountDown = CommonSmsCodeConstant.DEFAULT_TIMER;
      if(_timer != null){
        _timer.cancel();
        _timer = null;
      }
    }
    setState(() { });
  }
  
  ///网络请求发送验证码
  _httpSendSmsCode(String phone) {
    if(StringUtils.isEmpty(phone)){
      return;
    }
    if(!VgRegExpUtils.isPhone(phone)){
      toast("手机号格式不正确");
      return;
    }
    // if(ConstantRepository.getInstance().jumpAuthCodeEnable){
    //   toast("测试服不发送验证码～");
    //   return;
    // }
    // loading(true,msg: "获取中");
    _service ??= CommonSmsCodeService();
    _service?.serviceSendSmsCode(
        phone,
        BaseCallback(
            onSuccess: (val) {
              _isShowReset = true;
              // loading(false);
              toast("验证码已发送");
              _startTimer();
            },
            onError: (msg) {
              // loading(false);
              toast(msg);
            }));
  }

  ///默认获取验证码组件
  Widget _defaultChildWidget(){
    return Container(
      height: 44,
      padding: const EdgeInsets.symmetric(horizontal: 5),
      alignment: Alignment.center,
      child: Text(
        "获取验证码",
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
          fontSize: 13,
        ),
      ),
    );
  }

  ///默认倒计时组件
  Widget _defaultDownWidget(){
    return Container(
      height: 44,
      padding: const EdgeInsets.symmetric(horizontal: 5),
      alignment: Alignment.center,
      child: Text(
        "${_codeCountDown ?? 0}s",
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          color: ThemeRepository.getInstance().getTextMinorGreyColor_808388(),
          fontSize: 13,
        ),
      ),
    );
  }

  Widget _defaultResetChildWidget(){
    return Container(
      height: 44,
      padding: const EdgeInsets.symmetric(horizontal: 5),
      alignment: Alignment.center,
      child: Text(
        "重新获取",
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(
          color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
          fontSize: 13,
        ),
      ),
    );
  }

}
